<template>
	<view>
		<view class="images" v-if="imageSrc">
			<image :src="imageSrc" @click="chooseImage()" mode="widthFix" v-if="imageSrc"></image>
		</view>
		<view>
			<button @click="getWeather()">天气预报</button>
			<view v-if="weatherData">
				<view>日期：{{ weatherData.date }}</view>
				<view>星期：{{ weatherData.week }}</view>
				<view>最高温：{{ weatherData.high }}℃</view>
				<view>最低温：{{ weatherData.low }}℃</view>
			</view>
		</view>
		<view class="images">
			<button @click="download">下载图片</button>
			<img :src="loadimage" mode="widthFix" v-if="loadimage"></img>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imageSrc: "/static/xz2.jpg",
				weatherData: null,
				loadimage: ''
			}
		},
		methods: {
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const tempFilePaths = res.tempFilePaths[0];
						this.imageSrc = tempFilePaths;
						console.log(JSON.stringify(res.tempFilePaths));
						uni.previewImage({
							urls: res.tempFilePaths
						})
					}
				})
			},
			getWeather() {
				uni.request({
					 url: '/weatherApi/api/weather/city/101230501',
					method: 'GET',
					success: (res) => {
						console.log("天气预报---" + JSON.stringify(res.data));
						if (res.statusCode === 200) {
							const data = res.data;
							if (data.status === 200 && data.data?.forecast?.length > 1) {
								const tomorrow = data.data.forecast[1];
								this.weatherData = {
									date: tomorrow.date,
									week: tomorrow.week,
									high: tomorrow.high.replace('高温 ', ''),
									low: tomorrow.low.replace('低温 ', '')
								};
							} else {
								uni.showToast({
									title: '数据错误',
									icon: 'none'
								});
							}
						} else {
							uni.showToast({
								title: '请求失败：' + res.statusCode,
								icon: 'none'
							});
						}
					},
					fail: (res) => {
						console.log(res);
						uni.showToast({
							title: '网络异常',
							icon: 'none'
						});
					}
				});
			},
			download() {
				const imageUrl = 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg';
				uni.downloadFile({
					url: imageUrl,
					success: (downloadRes) => {
						if (downloadRes.statusCode === 200) {
							this.loadimage = downloadRes.tempFilePath;
						}
					},
					progress: (progressRes) => {
						    console.log('下载进度：' + progressRes.progress + '%');
					}
				})
			}
		}
	}
</script>

<style>
	.images {
		margin-top: 10rpx;
		padding: 10rpx;
		text-align: center;
	}

	.weather-info {
		margin-top: 20rpx;
		padding: 20rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
	}

	.weather-info view {
		margin-bottom: 10rpx;
	}
</style>